package com.bwie.service.impl;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.ModifierUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.mapper.*;
import com.bwie.poi.StringUtils;
import com.bwie.pojo.*;
import com.bwie.utils.KaptchaUtils;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import javafx.scene.paint.PhongMaterial;
import jodd.io.FileUtil;
import jodd.io.upload.FileUpload;
import org.aspectj.weaver.ast.Var;
import org.bouncycastle.dvcs.VSDRequestBuilder;
import org.checkerframework.checker.index.qual.SameLen;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.service.UserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.resource.HttpResource;
import sun.text.resources.es.FormatData_es_CL;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @Author: yiang
 * @Date:  2025/10/9 10:43
 * @Description: 
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    UserMapper userMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    HttpServletResponse response;

    @Autowired
    HotelMapper hotelMapper;

    @Autowired
    UserHotelMapper userHotelMapper;

    @Autowired
    RoomMapper roomMapper;

    @Autowired
    DictMapper dictMapper;

    @Autowired
    FastFileStorageClient fileStorageClient;

    @Autowired
    ImgsMapper imgsMapper;

    @Override
    public void getCode() {
        //获取随机数
        String code = RandomUtil.randomNumbers(4);
        //生成验证码
        KaptchaUtils.generateCaptcha(response,code);
        //存入Redis中
        redisTemplate.opsForValue().set("code",code,1, TimeUnit.MINUTES);

    }

    @Override
    public R getPhone(User user) {

        String senu = redisTemplate.opsForValue().get(user.getUserPhone() + "senu");
        if(StringUtils.isNotEmpty(senu)){
            return R.ERROR(500,"请在一分钟后发送");
        }

        //判断图片验证码
        if(StringUtils.isNotEmpty(user.getCode())){
            String code = redisTemplate.opsForValue().get("code");
            if(StringUtils.isNotEmpty(code)){
                if(!user.getCode().equals(code)){
                    return R.ERROR(500,"验证码错误");
                }
            }else{
                return R.ERROR(500,"验证码过期");
            }
        }else{
            return R.ERROR(500,"图片验证码为空");
        }
        //判断手机号
        User selectOne = userMapper.selectOne(
                new QueryWrapper<User>().lambda().eq(User::getUserPhone, user.getUserPhone())
        );
        if(selectOne==null){
            return R.ERROR(500,"手机号不存在");
        }
        //生成手机号验证码
        String phoneCode = RandomUtil.randomNumbers(4);
        //发送手机号验证码
        MobileMessageUtil.sendMobileMessage(user.getUserPhone(),phoneCode);
        //存入Redis中
        redisTemplate.opsForValue().set(user.getUserPhone(),phoneCode,5,TimeUnit.MINUTES);
        //在存入Redis中判断一分钟不能重复发送
        redisTemplate.opsForValue().set(user.getUserPhone()+"senu",phoneCode,1,TimeUnit.MINUTES);
        return R.OK();
    }

    @Override
    public R getLogin(User user) {
        //判断手机号验证码
        String rediscode = redisTemplate.opsForValue().get(user.getUserPhone());
        if(StringUtils.isEmpty(rediscode)){
            return R.ERROR(500,"手机号验证码过期");
        }

        if(!rediscode.equals(user.getPhoneCode())){
            return R.ERROR(500,"验证码错误");
        }

        //生成token
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie").claim("userPhone", user.getUserPhone()).compact();
        //存入Redis中
        redisTemplate.opsForValue().set("token-"+user.getUserPhone(),token,15,TimeUnit.MINUTES);
        //返回数据

        User one = userMapper.selectOne(
                new QueryWrapper<User>().lambda().eq(User::getUserPhone, user.getUserPhone())
        );

        one.setToken(token);
        return R.OK(one);
    }

    @Override
    public R PhoneById(User user) {
        //通过手机号获取用户Id
        User phoneId = userMapper.selectOne(
                new QueryWrapper<User>().lambda().eq(User::getUserPhone, user.getUserPhone())
        );
        //通过用户Id查询绑定酒店信息
        List<UserHotel> userHotels = userHotelMapper.selectList(
                new QueryWrapper<UserHotel>().lambda().eq(UserHotel::getUserId, phoneId.getUserId())
        );

        //通过酒店Id查询酒店信息
       List<Hotel> hotelList = new ArrayList<>();
        for (UserHotel userhotel : userHotels) {
            Hotel hotel = hotelMapper.selectById(userhotel.getHotelId());
            hotelList.add(hotel);
        }

        return R.OK(hotelList);
    }

    @Override
    public R upDateHotel(Hotel hotel) {

        Hotel byId = hotelMapper.selectById(hotel.getHotelId());

        if(byId==null){
            return R.ERROR(500,"酒店不存在");
        }

        hotelMapper.updateById(hotel);

        return R.OK();
    }

    @Override
    public R getRoom(Room room) {

        Page<Room> objectPage = new Page<>(room.getPageNum(), room.getPageSize());

        Page<Room> page = roomMapper.selectRoom(objectPage,room);
        //通过图片中的客房Id查询图片
        for (Room record : page.getRecords()) {
            List<Imgs> imgs = imgsMapper.selectList(
                    new QueryWrapper<Imgs>().lambda().eq(Imgs::getRoomId, record.getRoomId())
            );
            record.setImgs(imgs);
        }

        return R.OK(page);
    }

    @Override
    public R getDict(Integer type) {
        List<Dict> dicts = dictMapper.selectList(
                new QueryWrapper<Dict>().lambda().eq(Dict::getDictType, type)
        );
        return R.OK(dicts);
    }

    @Override
    public R roomAdd(Room room) {
        Room selectOne = roomMapper.selectOne(
                new QueryWrapper<Room>().lambda().eq(Room::getRoomName, room.getRoomName())
        );
        if(selectOne!=null){
            return R.ERROR(500,"名称已存在");
        }
        room.setRoomStatus(1);
        roomMapper.insert(room);

        //客房添加完成后 在图片的表中添加url
        for (Imgs img : room.getImgs()) {
            img.setRoomId(room.getRoomId());
            imgsMapper.insert(img);
        }

        return R.OK();
    }

    @Override
    public R AddImgs(MultipartFile file) {
        try {
            String extName = FileNameUtil.extName(file.getOriginalFilename());
            StorePath storePath = fileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extName, null);
            String page = "http://192.168.80.192:8888/"+storePath.getFullPath();
            return R.OK(page);
        } catch (IOException e) {
           e.printStackTrace();
            return R.ERROR(500,"上传失败");
        }


    }
}
